#include "thread.h"
#ifdef _WIN32
#include <process.h> //for _beginthreadex

Thread::Thread(Runnable *target /*= 0*/)
:_target(target)
,_handle(0) {

}

Thread::~Thread() {
    if (_handle != 0)
        CloseHandle(_handle);
    if (_target != 0)
        delete _target;
}

void Thread::start() {
    if (_handle != 0)
        return;
    unsigned id;
    _handle = reinterpret_cast<HANDLE>(
        _beginthreadex(0, 0, threadProc, this, 0, &id)
        );
}

void Thread::join() {
    if(_handle != 0) {
        WaitForSingleObject(_handle, INFINITE);
        CloseHandle(_handle);
        _handle = 0;
    }
}

unsigned __stdcall Thread::threadProc(void *param) {
    Thread *p = static_cast<Thread*>(param);
    if (p->_target != 0)
        p->_target->run();
    else
        p->run();
    return 0;
}
#else
Thread::Thread(Runnable *target):_target(target) {
	_handle = 0;
}

Thread::~Thread() {
	if(_handle!=0){
	pthread_detach(_handle);
	_handle = 0;
	}
}

void Thread::start() {
	pthread_create(&_handle, NULL, threadProc, (void*) this);
}

void Thread::join() {
	if(_handle!=0){
		pthread_join(_handle,0);
	}else{

	}
}
void* Thread::threadProc(void *param) {

    Thread *p = static_cast<Thread*>(param);
    if (p->_target != 0)
        p->_target->run();
    else
        p->run();
    return 0;
}
#endif
